<template>
  <div class="owner-info-container">
    <div class="owner-info-header">
      <h1>业主信息管理</h1>
      <div class="owner-stats">
        <div class="stat-card">
          <span class="stat-icon">📞</span>
          <div class="stat-content">
            <h3>联系方式</h3>
            <p>{{ owner.contactInfo || '暂未录入' }}</p>
          </div>
        </div>
      </div>
    </div>

    <div class="info-section">
      <div class="info-card">
        <h2>个人信息</h2>
        <form @submit.prevent="updateOwner" class="owner-form">
          <div class="form-group">
            <label for="name">姓名</label>
            <input 
              id="name" 
              v-model="owner.name" 
              type="text" 
              placeholder="请输入您的姓名"
              required
            />
          </div>
          <div class="form-group">
            <label for="contactInfo">联系方式</label>
            <input 
              id="contactInfo" 
              v-model="owner.contactInfo" 
              type="text" 
              placeholder="请输入手机号码"
              required
            />
          </div>
          <button type="submit" class="update-button">
            <span class="button-icon">✔️</span>
            更新信息
          </button>
        </form>
      </div>

      <div class="complaint-card">
        <h2>投诉建议</h2>
        <form @submit.prevent="submitComplaint" class="complaint-form">
          <div class="form-group">
            <label for="complaintType">类型</label>
            <select 
              id="complaintType" 
              v-model="complaintType" 
              class="form-control"
            >
              <option value="complaint">投诉</option>
              <option value="suggestion">建议</option>
            </select>
          </div>
          <div class="form-group">
            <label for="complaintContent">详细描述</label>
            <textarea 
              id="complaintContent"
              v-model="complaintContent" 
              placeholder="请详细描述您的投诉或建议（至少10个字符）"
              required
              minlength="10"
              @input="validateComplaint"
            ></textarea>
            <span v-if="complaintError" class="error-text">{{ complaintError }}</span>
          </div>
          <button type="submit" class="submit-button">
            <span class="button-icon">📝</span>
            提交投诉
          </button>
        </form>
      </div>
    </div>

    <!-- 新增密码重置模块 -->
    <div class="password-reset-card">
      <h2>密码重置</h2>
      <form @submit.prevent="resetPassword" class="password-reset-form">
        <div class="form-group">
          <label for="oldPassword">当前密码</label>
          <input 
            id="oldPassword" 
            v-model="passwordReset.oldPassword" 
            type="password" 
            placeholder="请输入当前密码"
            required
          />
        </div>
        <div class="form-group">
          <label for="newPassword">新密码</label>
          <input 
            id="newPassword" 
            v-model="passwordReset.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            required
            :pattern="passwordPattern"
            title="密码必须包含字母和数字，长度8-16位"
          />
        </div>
        <div class="form-group">
          <label for="confirmPassword">确认新密码</label>
          <input 
            id="confirmPassword" 
            v-model="passwordReset.confirmPassword" 
            type="password" 
            placeholder="再次输入新密码"
            required
          />
        </div>
        <button type="submit" class="reset-password-button">
          <span class="button-icon">🔐</span>
          重置密码
        </button>
      </form>
    </div>

    <!-- 新增用户名修改模块 -->
    <div class="username-change-card">
      <h2>修改用户名</h2>
      <form @submit.prevent="changeUsername" class="username-change-form">
        <div class="form-group">
          <label for="currentUsername">当前用户名</label>
          <input 
            id="currentUsername" 
            :value="user.username" 
            type="text" 
            disabled
          />
        </div>
        <div class="form-group">
          <label for="newUsername">新用户名</label>
          <input 
            id="newUsername" 
            v-model="usernameChange.newUsername" 
            type="text" 
            placeholder="请输入新用户名"
            required
            minlength="4"
            maxlength="20"
          />
        </div>
        <div class="form-group">
          <label for="password">确认密码</label>
          <input 
            id="password" 
            v-model="usernameChange.password" 
            type="password" 
            placeholder="请输入当前密码"
            required
          />
        </div>
        <button type="submit" class="change-username-button">
          <span class="button-icon">🔄</span>
          修改用户名
        </button>
      </form>
    </div>

    <!-- 通知消息 -->
    <div v-if="error" class="notification error">{{ error }}</div>
    <div v-if="success" class="notification success">{{ success }}</div>
  </div>
</template>

<script>
export default {
  name: 'OwnerInfoPage',
  data() {
    return {
      owner: {
        name: '',
        contactInfo: '',
      },
      complaintType: 'service',
      complaintContent: '',
      error: null,
      success: null,
      passwordReset: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordPattern: '^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,16}$',
      user: JSON.parse(localStorage.getItem('user')),
      usernameChange: {
        newUsername: '',
        password: ''
      },
      complaintError: ''
    }
  },
  methods: {
    async fetchOwnerInfo() {
      const user = JSON.parse(localStorage.getItem('user'));
      const ownerId = user ? user.ownerId : null;
      if (!ownerId) {
        this.error = '未找到业主信息，请重新登录。';
        return;
      }
      try {
        const response = await fetch(`http://localhost:8080/api/owners/${ownerId}`);
        if (!response.ok) throw new Error('获取业主信息失败');
        this.owner = await response.json();
      } catch (err) {
        this.error = err.message;
      }
    },
    async updateOwner() {
      if (!this.user || !this.user.ownerId) {
        this.error = '未找到业主信息，请重新登录。';
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(this.owner.contactInfo)) {
        this.error = '请输入有效的手机号码';
        return;
      }

      try {
        const requestData = {
          name: this.owner.name,
          contactInfo: this.owner.contactInfo,
          propertyId: this.user.propertyId
        };

        const response = await fetch(`http://localhost:8080/api/owners/${this.user.ownerId}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
        });

        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(errorText || '更新业主信息失败');
        }

        const updatedOwner = await response.json();
        this.success = '业主信息更新成功！';
        
        localStorage.setItem('user', JSON.stringify({
          ...this.user,
          name: updatedOwner.name,
          contactInfo: updatedOwner.contactInfo
        }));

        this.owner = {
          ...this.owner,
          name: updatedOwner.name,
          contactInfo: updatedOwner.contactInfo
        };
      } catch (err) {
        this.error = err.message;
      }
    },
    async submitComplaint() {
      if (!this.user || !this.user.ownerId) {
        this.error = '未找到业主信息，请重新登录。';
        return;
      }

      if (this.complaintContent.trim().length < 10) {
        this.error = '投诉内容至少需要10个字符';
        return;
      }

      try {
        const complaintData = {
          type: this.complaintType === 'other' ? 'suggestion' : 'complaint',
          content: this.complaintContent.trim(),
          status: 'open',
          owner_id: this.user.ownerId
        };

        const response = await fetch('http://localhost:8080/api/complaints', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(complaintData)
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || '提交投诉失败');
        }

        this.success = '投诉提交成功！我们将尽快处理您的建议。';
        
        // 重置表单
        this.complaintContent = '';
        this.complaintType = 'service';
        this.complaintError = '';
      } catch (err) {
        this.error = err.message;
      }
    },
    async resetPassword() {
      if (!this.user || !this.user.ownerId) {
        this.error = '未找到用户信息，请重新登录';
        return;
      }

      if (!new RegExp(this.passwordPattern).test(this.passwordReset.newPassword)) {
        this.error = '新密码必须包含字母和数字，长度8-16位';
        return;
      }

      if (this.passwordReset.newPassword !== this.passwordReset.confirmPassword) {
        this.error = '两次输入的密码不一致';
        return;
      }

      try {
        const requestData = {
          oldPassword: this.passwordReset.oldPassword,
          newPassword: this.passwordReset.newPassword
        };

        const response = await fetch(`http://localhost:8080/api/owners/${this.user.ownerId}/password`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || '密码修改失败');
        }

        this.success = '密码修改成功！';
        this.passwordReset = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        };
      } catch (err) {
        this.error = err.message;
      }
    },
    async changeUsername() {
      if (!this.user || !this.user.ownerId) {
        this.error = '未找到用户信息，请重新登录';
        return;
      }

      if (this.usernameChange.newUsername.length < 4) {
        this.error = '用户名长度至少4个字符';
        return;
      }

      if (this.usernameChange.newUsername === this.user.username) {
        this.error = '新用户名不能与当前用户名相同';
        return;
      }

      try {
        const requestData = {
          name: this.owner.name,
          username: this.usernameChange.newUsername
        };

        const response = await fetch(`http://localhost:8080/api/owners/${this.user.ownerId}/basic-info`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || '用户名修改失败');
        }

        const updatedOwner = await response.json();
        this.success = '用户名修改成功！';
        
        localStorage.setItem('user', JSON.stringify({
          ...this.user,
          username: updatedOwner.username,
          name: updatedOwner.name
        }));

        this.user = JSON.parse(localStorage.getItem('user'));

        this.usernameChange = {
          newUsername: '',
          password: ''
        };
      } catch (err) {
        this.error = err.message;
      }
    },
    validateComplaint() {
      if (this.complaintContent.trim().length < 10) {
        this.complaintError = '投诉内容至少需要10个字符';
      } else {
        this.complaintError = '';
      }
    }
  },
  created() {
    this.fetchOwnerInfo();
  }
}
</script>

<style scoped>
.owner-info-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  background-color: var(--gray-light);
}

.owner-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.owner-info-header h1 {
  font-size: 2rem;
  color: var(--text-color);
}

.owner-stats {
  display: flex;
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  background-color: white;
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  font-size: 2rem;
  margin-right: 15px;
}

.stat-content h3 {
  font-size: 0.9rem;
  color: var(--gray);
  margin-bottom: 5px;
}

.stat-content p {
  font-size: 1.2rem;
  font-weight: 600;
  color: var(--text-color);
}

.info-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.info-card, .complaint-card {
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.info-card h2, .complaint-card h2 {
  font-size: 1.5rem;
  color: var(--text-color);
  margin-bottom: 20px;
  text-align: center;
}

.owner-form, .complaint-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 0.9rem;
  color: var(--text-color);
}

input, select, textarea {
  padding: 12px;
  border: 1px solid var(--gray);
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

input:focus, select:focus, textarea:focus {
  outline: none;
  border-color: var(--primary-color);
}

textarea {
  min-height: 120px;
  resize: vertical;
}

.update-button, .submit-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.update-button:hover, .submit-button:hover {
  background-color: var(--secondary-color);
}

.button-icon {
  font-size: 1.2rem;
}

.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px;
  border-radius: 8px;
  z-index: 1100;
}

.error {
  background-color: #fff5f5;
  color: #ff6b6b;
}

.success {
  background-color: #f0fdf4;
  color: #4ecdc4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-section {
    grid-template-columns: 1fr;
  }

  .owner-info-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .owner-stats {
    width: 100%;
    justify-content: space-between;
  }
}

/* 新增密码重置卡片样式 */
.password-reset-card {
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  margin-top: 30px;
}

.password-reset-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.reset-password-button {
  background-color: #ff6b6b;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.reset-password-button:hover {
  background-color: #ff5252;
}

/* 新增用户名修改卡片样式 */
.username-change-card {
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  margin-top: 30px;
}

.username-change-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.change-username-button {
  background-color: #4ecdc4;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.change-username-button:hover {
  background-color: #45b7aa;
}

/* 禁用输入框样式 */
input:disabled {
  background-color: #f4f4f4;
  cursor: not-allowed;
}

.error-text {
  color: #ff6b6b;
  font-size: 0.8rem;
  margin-top: 5px;
}
</style> 